package ueb15;


import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JPanel;

import ueb15.Node;
import ueb15.Tree;

/**
 * This is the panel, where the tree gets drawn.
 */
public class RedBlackTreeComponent extends JPanel {
	private static int height = 600;
	private static final long serialVersionUID = 1L;
	private static int width = 800;

	private final Controller controller;

	public RedBlackTreeComponent(Controller controller) {
		this.controller = controller;
		setPreferredSize(new Dimension(width, height));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
	 */
	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		Tree tree = controller.getTree();
		if (tree == null) {
			paintEmpty(g);
		} else {
			paintTree(g);
		}
	}

	public void paintNode(Node node, Graphics g, int x, int y, int separation) {
		final int R = 20;

		if (node.getLeftChild() != null) {
			int xx = x - separation;
			int yy = y + R * 3;
			g.setColor(java.awt.Color.BLACK);
			g.drawLine(x, y, xx, yy);
			paintNode(node.getLeftChild(), g, xx, yy, separation / 2);
		}

		if (node.getRightChild() != null) {
			int xx = x + separation;
			int yy = y + R * 3;
			g.setColor(java.awt.Color.BLACK);
			g.drawLine(x, y, xx, yy);
			paintNode(node.getRightChild(), g, xx, yy, separation / 2);
		}

		if (node.isBlack()) {
			g.setColor(java.awt.Color.BLACK);
		} else {
			g.setColor(java.awt.Color.RED);
		}
		g.fillOval(x - R, y - R, 2 * R, 2 * R);

		g.setColor(java.awt.Color.WHITE);
		if (node.getiData() != null) {
			g.drawString("" + node.getiData(), x - 3, y + 5);
		} else {
			g.drawString("nil", x - 7, y + 5);
		}
	}

	private void paintEmpty(Graphics g) {
		g.setColor(Color.RED);
		g.fillRect(0, 0, width, height);
		g.setColor(Color.WHITE);
		g.drawString("No tree!", width / 2, height / 2);
	}

	private void paintTree(Graphics g) {
		Tree tree = controller.getTree();
		paintNode(tree.getRoot(), g, width / 2, 20, 100);
	}

}
